<?php
namespace Pig\Controller;
use \Pig\Util\Page;

class CouponController extends BaseController {
    public $tca = array();
    public $tbName = CONTROLLER_NAME;

    /**
     * 高级搜索
     + 数据说明
     + label    页面显示数据
     + name     数据库字段名
     + type     搜索类型(目前只支持input及select的搜索)
     + data     select框所有数据(在init函数中赋值,input类型,此项为空)
     + value    接收页面传值并在搜索之后在页面展示
     + category 针对input的类型(normal代表普通的input,time代表时间搜索的input),select类型无此数据
     */
    public $search = array(
    );

    /**
     * 数据操作(权限管理)
     + 数据说明(目前只支持添加,数据导入,数据导出----注意方法名需保持跟权限表的添加的数据一致)
     + label     页面显示操作权限
     + access    操作方法
     + class     页面显示样式
     */
    public $action = array(
        array('label' => '添加', 'access' => 'save', 'class' => 'icon-plus')
    );

    /**
     * 管理操作(权限管理)
     + 数据说明(注意方法名需保持跟权限表的添加的数据一致)
     + label     页面显示操作权限
     + access    操作方法
     */
    public $edit_action = array(
        array('label' => '编辑', 'access' => 'edit', 'class' => 'btn green-stripe mini','type' => 'link'),
        array('label' => '删除', 'access' => 'del', 'class' => 'btn red-stripe mini del', 'type' => 'link'),
    );

    /**
     * 操作管理(数据删除,发布,草稿,置顶,不顶,热门,不热等操作)
     + 数据说明(确保数据表中有相关参数,若需要添加特殊操作,应先在BaseController下添加相关操作方法)
     + label     页面显示操作内容
     + access    操作方法
     */
    public $handle = array(
    );

    /**
     * 列表页表头展示内容
     + 数据说明(确保数据表中有相关参数,若需要添加特殊操作,应先在BaseController下添加相关操作方法)
     + label     页面显示操作内容
     + field     字段名
     + status    编辑状态(true为列表页可编辑,false为不能编辑)
     */
    public $index_content = array(
        array('label' => 'ID编号', 'field' => 'id', 'status' => false),
        array('label' => '标题', 'field' => 'name', 'status' => false),
        array('label' => '类型', 'field' => 'type', 'status' => false),
        array('label' => '面值', 'field' => 'money', 'status' => false),
        array('label' => '领取数量', 'field' => 'receive', 'status' => false),
        array('label' => '使用数量', 'field' => 'used', 'status' => false),
        array('label' => '适用金额', 'field' => 'full_money', 'status' => false),
        array('label' => '关联商品', 'field' => 'goods_id', 'status' => false),
        array('label' => '有效期', 'field' => 'expired', 'status' => false),
    );


    protected function init() {
        //高级筛选
        $this->assign('status_all', $this->status_all);

        //数据操作(权限管理)
        $this->assign('action', $this->action);

        //管理操作
        $this->assign('edit_action', $this->edit_action);

        //操作管理
        $this->assign('handle', $this->handle);
        $type = I('request.type','');
        $except = ['goods_id','full_money'];
        if($type){
            foreach ($this->index_content as $key => $value) {
                if(in_array($value['field'],$except)){
                    unset($this->index_content[$key]);
                }
            }
        }
        if(I('request.id')){
            $info = D($this->tbName)->find(I('request.id'));
            if($info['type'] == 3){
                $type = 3;
            }
        }
        //列表页表头展示内容
        $this->assign('index_content', $this->index_content);
        $info = [];
        if (ACTION_NAME == 'edit') {
            $id = I('param.id');
            $info = M($this->tbName)->where('id = ' . $id)->find();
        }

        /*商品*/
        $Goods = M('goods');
        $result = $Goods->where(array('deleted' => 0))->Field('id as "0", name as "1"')->select();
        $goods_html = '';
        foreach ($result as $key => $value) {
            $select = $value[0] == $info['goods_id']?'selected="selected"':'';
            $goods_html .= '<option value="'.$value[0].'"'.$select.'>'.$value[1].'</option>';
        }
        //配置字段
        $this->tca = array(
            'name' => array(
                'label' => '标题',
                'type' => 'text',
                'required' => true,
                'disabled' => ACTION_NAME == 'edit'?true:false
            ),
            'type' => array(
                'label' => '类型',
                'type' => $type?'label':'radio',
                'data' => $type?'新人大礼包':[
                    [1,'满减'],
                    [2,'立减']
                ],
                'default' => 1,
                'disabled' => ACTION_NAME == 'edit'?true:false
            ),
            'goods_id' => array(
                'label' => '适用商品',
                'type' => 'select_tree',
                'data' => $goods_html,
                'validate' => [
                    ['/\\d/','请选择适用商品']
                ],
                'relation' => ['type',2],
                'disabled' => ACTION_NAME == 'edit'?true:false
            ),
            'full_money' => array(
                'label' => '使用门槛',
                'type' => 'text',
                'vilidate' => [
                    ['/\\d/','请填写正确的使用门槛']
                ],
                'relation' => ['type',1],
                'help' => '使用门槛为0或正整数',
                'disabled' => ACTION_NAME == 'edit'?true:false
            ),
            'money' => array(
                'label' => '面值',
                'type' => 'text',
                'required' => true,
                'vilidate' => [
                    ['/^[1-9]*\d$/','请填写正确的使用面值']
                ],
                'help' => '面值为正整数',
                'disabled' => ACTION_NAME == 'edit'?true:false
            ),
            'expired' => array(
                'label' => '有效期',
                'type' => 'text',
                'required' => true,
                'vilidate' => [
                    ['/^[1-9]*\d$/','请填写正确的有效期']
                ],
                'help' => '有效期为正整数,单位为天',
                'disabled' => ACTION_NAME == 'edit'?true:false
            )
        );
        if($type){
            foreach ($except as $key => $value) {
                unset($this->tca[$value]);
            }
        }
    }

    /**
     * 列表页面
     */
    public function index() {
        $this->init(); //加载初始化数据
        $Obj = D($this->tbName); //实例化对象

        $Where = "deleted=0";
        if(I('request.type')){
            $Where .= " and type = 3";
        }else{
            $Where .= " and type IN (1,2)";
        }
        $sorting = I('get.sorting') ? I('get.sorting') : 'id';
        $order = I('get.order') ? I('get.order') : 'desc';
        $limit_num = $_SESSION['page_limit_num'] ? $_SESSION['page_limit_num'] : 10;
        
        $Page = new Page($Obj->where($Where)->count(), $limit_num); // 实例化分页类 传入总记录数和每页显示的记录数
        $list = $Obj->where($Where)->order($sorting . ' ' . $order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $UserCoupon = M('user_coupon');
        if($list){
            $Goods = M('goods');
            foreach ($list as $key => &$value) {
                $value['full_money'] = $value['type'] == 1?$value['full_money']:'--';
                $value['goods_id'] = $value['type'] == 2?$Goods->where(['id' => $value['goods_id']])->getField('name'):'--';
                $value['type'] = $value['type'] == 3?'新人大礼包':($value['type'] == 1?'满减':'立减');
                $value['receive'] = $UserCoupon->where(array('coupon_id' => $value['id']))->count();
                $value['used'] = $UserCoupon->where(array('coupon_id' => $value['id'],'used_time' => array('gt',0)))->count();
            }
        }
        $this->assign('list', $list); // 赋值数据集
        $this->assign('page', $Page->show()); // 分页显示输出 
        $this->display(); // 输出模板
    }

    /**
     * 编辑数据
     */
    public function edit() {
        $this->save();
    }
    /**
     * 保存数据
     */
    public function save() {
        try{
            $this->init();
            //编辑数据
            $id = I('request.id') ? I('request.id') : null;
            $info = M($this->tbName)->where('id = ' . $id)->find();
            if (IS_POST) {
                $type = I('request.type','');
                if(!in_array($type,[1,2,3])){
                    $this->error('优惠券类型错误');
                }
                /*if($type && $type != 3){
                    $this->error('优惠券类型错误');
                }*/
                foreach ($_POST as $key => $val) {
                    if(is_array($val)){
                        $_POST[$key] = implode(',', $val);
                    }
                    if(@$this->tca[$key]['required'] && !$val){
                        $this->error($this->tca[$key]['label'] . '*是必填项!');
                    }
                    //数据验证
                    if(isset($this->tca[$key]['validate'])){
                        //是否存在关联数据
                        if(isset($this->tca[$key]['relation'])){
                            //判断关联数据值类型 进入不同的判断表达式 只支持字符串，数组两种类型
                            if(is_array($this->tca[$key]['relation'][1])){
                                if(in_array($_POST[$this->tca[$key]['relation'][0]],$this->tca[$key]['relation'][1])){
                                    foreach ($this->tca[$key]['validate'] as $value) {
                                        if(!preg_match($value[0], $val)){
                                            $this->error($value[1]);
                                        }
                                    }
                                }
                            }else{
                                if($_POST[$this->tca[$key]['relation'][0]] == $this->tca[$key]['relation'][1]){
                                    foreach ($this->tca[$key]['validate'] as $value) {
                                        if(!preg_match($value[0], $val)){
                                            $this->error($value[1]);
                                        }
                                    }
                                }
                            }
                        }else{
                            foreach ($this->tca[$key]['validate'] as $value) {
                                if(!preg_match($value[0], $val)){
                                    $this->error($value[1]);
                                }
                            }
                        }
                    }
                }
                if($type){
                    $_POST['type'] = $type;
                }
                $Obj = D($this->tbName);
                $result = $Obj->create();
                if (!$result) {
                    $this->error($Obj->getError());
                } else {   
                    if ($id) {
                        $Obj->tstamp = time();
                        $id = $Obj->where(array('id' => $id))->save();
                        $message = '编辑成功!';
                    } else {
                        $Obj->crdate = time();
                        $Obj->tstamp = time();
                        $id = $Obj->add();
                        $message = '添加成功!';
                    }
                    if($id){
                        if($type == 3){
                            $this->success($message, U(CONTROLLER_NAME . '/index', 'kept=1&type=3'));
                        }else{
                            $this->success($message, U(CONTROLLER_NAME . '/index', 'kept=1'));
                        }
                        exit;
                    }else{
                        debug($Obj->_sql());
                        $this->error('保存失败');
                        exit;
                    }
                    
                }
            }
            //自动渲染字段
            parent::autoFields($this->tca, $info);
            $this->display('info');
        }catch(\Exception $e){
            debug($e->getmessage());
            $message = IS_AJAX?'保存失败':'';
            $this->error($message);
        }
    }
}

?>